#!/bin/bash
#set -x -v 

# MW. Lib search / show program

# usage liblook libname [text_to_find] [l_before] [l_after]

LIBPATH=/usr/local/lib

function trapper()
    {
     echo User break! 
     echo Exiting . . .
     unset LIBPATH
     exit 1
    }
    
trap trapper SIGINT SIGQUIT 

function operror()
    {
     echo Incorrect parameters: $*, $#
     echo Usage: liblook libname [text_to_find] [l_before] [l_after]
     unset LIBPATH
     exit 2
    }

function showlib()
    {
     if test -f $LIBPATH/$1; then 
         less $LIBPATH/$1; exit 0; fi
	 
     if test -f [C./$1; then
         less ./$1; exit 0; fi
	     
     echo Searching $1 in ~/ . . . 	 
     less $(find ~/ -name $1) 
    }

function searchlib()
    {
    if test -f $LIBPATH/$1; then 
        echo File: $1; echo;
        grep -B"$3" -A"$4" --ignore-case -e "$2" $LIBPATH/$1; 
	echo; exit 0; fi
	 
     if test -f ./$1; then
        echo File: $1; echo; 
        grep -B"$3" -A"$4" --ignore-case -e "$2" ./$1; 
	echo; exit 0; fi
	     
#if *.lib or sth like this

     echo Searching $1 in ~/ . . .;echo;
     if (grep -B"$3" -A"$4" --ignore-case -e "$2" $(find ~/ -name $1)); then 
	echo; exit 0; fi

     echo Searching $1 in $LIBPATH;echo;
     if (grep -B"$3" -A"$4" --ignore-case -e "$2" $(find $LIBPATH -name $1)); then
         echo; exit 0; fi

    }
    

# Main body
if test $# -lt 1 -o $# -gt 4; then operror $*; fi

case $# in
1) showlib $*;;
2) searchlib $1 $2 2 2;;
3) searchlib $1 $2 $3 2;;
4) searchlib $1 $2 $3 $4;;
esac

unset LIBPATH
exit 0

